import { loginApi } from '@/api/api'
import layout from '@/layout'
import { allPages, asyncRoutes, constantRoutes } from '@/router'
import request from '@/utils/requests'
import { defineStore } from 'pinia'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 * 判断用户是否有权限访问单个路由
 * roles 用户角色
 * route 访问的路由
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some((role) => route.meta.roles.includes(role))
  } else {
    return true
  }
}
// //这一步是取出来view里面的文件找到对应文件的懒加载函数，并执行。
const loadView = (view) => {
  const routeAllPathToCompMap = import.meta.glob('@/views/**/*.vue')
  // let dataRouter
  for (const path in routeAllPathToCompMap) {
    const dir =
      '/' +
      path
        .split('views/')[1]
        .split('.vue')[0]
        .replace(/\.\//g, '/')
        .replace(/\.vue/g, '')
        .replace(/\/index/, '')
    if (dir === view) {
      return routeAllPathToCompMap[path]
    }
  }
  // return dataRouter;
}
/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 * 筛选可访问的动态路由
 * roles 用户角色
 * route 访问的动态列表
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []
  routes.forEach((route) => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

//二维数组转树
const arrayToTree = (
  array,
  { id = 'id', pid = 'pid', children = 'children', rootId = null } = {}
) => {
  const tree = array
  // console.log('array',array)
  // debugger
  tree.forEach((item) => {
    let index = tree.findIndex((item1) => item1[id] === item[pid])
    // console.log('item',index)
    if (index !== -1) {
      tree[index][children] = tree[index][children] || []
      tree[index][children].push(item)
    }
  })
  return tree.filter((item) => item[pid] === rootId)
}

// pinia状态管理
export const usePermissionStore = defineStore('permission', {
  state: () => {
    return {
      routes: [],
      userBtnList: [],
      addRoutes: []
    }
  },
  getters: {
    permission_routes: (state) => state.routes
  },
  actions: {
    // 生成路由
    async createRouters({ commit }) {
      // 在登录时获取菜单信息，并生成菜单
      const { data } = await request(loginApi.getStaffMenuList)
      let num = 0
      // 返回主菜单
      let routers = data.filter((item) => {
        return (
          (item.status && allPages[item.component] && item.menuType === '2') || item.menuType === 5
        )
      })
      // 返回按钮或者字段
      const fieldOrBtnRouters = data.filter((item) => {
        return item.status && (item.menuType === '3' || item.menuType === '4')
      })
      // 给state的userBtnList赋值 相当于vuex的commit('XX', XX)
      this.userBtnList = fieldOrBtnRouters


      // 循环菜单
      routers = routers.map((item) => {
        const tmp = {}
        tmp.path = item.component === '@/layout' ? '/' + item.component + num : item.component

        if (item.component === '@/layout') {
          tmp.component = layout
        } else {
          tmp.component = allPages[item.component]
        }

        tmp.name = item.id
        tmp.meta = {}
        tmp.meta.title = item.name
        tmp.meta.icon = item.icon
        tmp.parentId = item.parentId
        tmp.id = item.id
        tmp.hidden = item.menuType === '5'

        num++
        return tmp
      })

      // console.log(123, routers)
      routers = arrayToTree(routers, { pid: 'parentId', rootId: '0' })
      // console.log('树状路由', routers)
      routers.forEach((item) => {
        if (item && item.children) {
          item.path = '/' + item.children[0].path.split('/')[1]
        }
      })

      routers = routers.concat(asyncRoutes)
      const indexArr = {
        path: '/',
        redirect: '/dashboard',
        name: 'Menudashboard',
        meta: { title: '工作台', icon: 'dashboard', affix: true },
        component: () => import('@views/dashboard/index.vue')
      }
      return new Promise((resolve) => {
        // 赋值给state的routes

        routers = constantRoutes.concat(routers)

        this.addRoutes = routers
        this.addRoutes.unshift(indexArr)
        // this.routes = routers
        // console.log('routers123', routers)
        resolve(routers)
      })
    }
  }
})

export default usePermissionStore
